<?php

namespace application\controllers;

use application\BaseController;
use fastphp\facade\Db;
use fastphp\facade\Request;
use fastphp\facade\Session;
use fastphp\util\Directory;
use fastphp\util\Header;
use fastphp\util\Utils;

class AdminMenuController extends BaseController
{
    public function baseIndex()
    {
        $param = Request::param();
        if (Request::isGet()) {
            if (!empty($param)) {
//                Session::clear('crumbs');
                $data = [];
                if (!empty(Session::get('crumbs'))) {
                    $data[] = json_decode(Session::get('crumbs'));
                }
                $data[] = ['name' => $param['name'], 'url' => $param['url']];
                $restructuredArray = [];
                foreach ($data as $key => $value) {
                    if (is_array($value) && count($value) && is_object($value[0] ?? [])) {
                        // 处理包含stdClass对象的数组
                        foreach ($value as $obj) {
                            $restructuredArray[] = [
                                'name' => $obj->name,
                                'url' => $obj->url,
                            ];
                        }
                    } elseif (is_array($value)) {
                        // 处理普通的关联数组
                        $restructuredArray[] = [
                            'name' => $value['name'],
                            'url' => $value['url'],
                        ];
                    }
                }
                $ls = Utils::array_unique_multidimensional($restructuredArray);
                $index = 0;
                for ($j = 0; $j < count($ls); $j++) {
                    if (($ls[$j]['name'] == $param['name']
                        && $ls[$j]['url'] == $param['url'])) {
                        $index = $j;
                    }
                }
                for ($k = 0; $k < count($ls); $k++) {
                    if ($k > $index) {
                        unset($ls[$k]);
                    }
                }
                Session::set('crumbs', json_encode($ls));

                if (!empty($param['parent_id'])) {
                    Session::set('parent_id', $param['parent_id']);
                    $this->_view->set('parent_id', $param['parent_id']);
                } else {
                    Session::clear('parent_id');
                }

                $this->_view->set("crumbs", $ls);
            }
            $this->_view->render();
        } else {
            $filed = 'a.id,b.name as parent_id,a.name,a.url,a.order_num,a.created_at,a.updated_at,a.status';
            if (!empty($param)) {
                $parent_id = $param['parent_id'];
                if (!empty($parent_id)) {
                    $res = Db::table('admin_menus')
                        ->alias('a')
                        ->leftJoin('admin_menus b', 'b.id = a.parent_id')
                        ->where('a.parent_id', $parent_id)
                        ->field($filed)
                        ->page($param['page'] ?? 1,
                            $param['limit'] ?? 10)
                        ->select();
                } else {
                    $res = Db::table('admin_menus')
                        ->alias('a')
                        ->leftJoin('admin_menus b', 'b.id = a.parent_id')
                        ->field($filed)
                        ->page($param['page'] ?? 1,
                            $param['limit'] ?? 10)
                        ->select();
                }
            } else {
                $res = Db::table('admin_menus')
                    ->alias('a')
                    ->leftJoin('admin_menus b', 'b.id = a.parent_id')
                    ->field($filed)
                    ->select();
            }
            for ($i = 0; $i < count($res); $i++) {
                $parent_id = $res[$i]['parent_id'];
                $status = $res[$i]['status'];
                $res[$i]['parent_id'] = $parent_id ?? '无';
                $res[$i]['status'] = $status ? '启用' : '关闭';
            }

            $this->json('', $res, 0, ['count' => count($res)]);
        }

    }

    public function baseAdd()
    {
        $param = Request::param();
        if (Request::isGet()) {
            $parents = Db::table('admin_menus')
                ->field('id,name')
                ->select();
            $parent_id = Session::get('parent_id') ?? 0;
            if (!empty($parent_id)) {
                $sql = "SHOW TABLES";
                $db = new Db();
                $tables = $db->sql_query($sql);
//                var_dump($tables);
                $this->_view->set('tables', $tables);
            }
            $this->_view->set('parent_id', $parent_id);
            $this->_view->set('parents', $parents);
            $this->_view->render();
        } else {
            if (!empty($param['table_name'])) {
//                  'Field' => string 'id' (length=2)
//                  'Type' => string 'int(11)' (length=7)
//                  'Null' => string 'NO' (length=2)
//                  'Key' => string 'PRI' (length=3)
//                  'Default' => null
//                  'Extra' => string 'auto_increment' (length=14)

                $tableName = $param['table_name'];
                // 准备SQL查询语句
                $sql = "SHOW COLUMNS FROM $tableName";
                $db = new Db();
                $table = $db->sql_query($sql);
//                var_dump($table);
                $parent_id = Session::get('parent_id') ?? 0;
                $info = Db::table('admin_menus')
                    ->where('id', $parent_id)
                    ->find();

                $preName = ucfirst(str_replace(DB_TABLE_PREFIX, "", $tableName));
                if (strpos($preName, "_") !== false) {
                    $tmp = "";
                    $preName = explode("_", $preName);
                    foreach ($preName as $item) {
                        $tmp .= ucfirst($item);
                    }
                    $preName = $tmp;
                }
                $dirPath1 = APP_PATH . 'application/views/' . $preName;
                if (!is_dir($dirPath1)) {
                    if (!Directory::createDirectoryRecursively($dirPath1)) {
                        return;
                    };
                }
                $filePath1 = $dirPath1 . '/' . 'index' . SMARTY_SUF;
                $filePath2 = $dirPath1 . '/' . 'add' . SMARTY_SUF;
                $filePath3 = $dirPath1 . '/' . 'update' . SMARTY_SUF;

                $fp = fopen($filePath1, 'w');
                $indexTop = str_replace('base', $param['url'], file_get_contents(TPL_PATH . 'indexTop' . SMARTY_SUF));
                $indexBottom = str_replace('base', $param['url'], file_get_contents(TPL_PATH . 'indexBottom' . SMARTY_SUF));
                $midData = [
                    [
                        'type' => 'checkbox', 'fixed' => 'left'
                    ],
                ];
//                {field: 'id', title: 'Id', width: 90, sort: true, fixed: 'left'}
                foreach ($table as $item) {
                    $field = $item['Field'];
                    if (strpos($field, '_img') !== false
                        || strpos($field, '_image') !== false) {
                        $midData[] = [
                            'field' => $item['Field'],
                            'title' => ucfirst($item['Field']),
                            'width' => 150,
                            'templet' => "<div><img src='../../../{{d.$field}}' width='50' height='50' /></div>"];
                    } else {
                        $midData[] = [
                            'field' => $item['Field'],
                            'title' => ucfirst($item['Field']),
                        ];
                    }

                }
                $midData[] = [
                    'fixed' => 'right', 'title' => '操作', 'align' => 'center', 'toolbar' => '#barDemo'
                ];
                $data = $indexTop . json_encode($midData) . $indexBottom;
                fwrite($fp, $data);
                fclose($fp);


                $fp = fopen($filePath2, 'w');
                $addTop = str_replace('base', $param['url'], file_get_contents(TPL_PATH . 'addTop' . SMARTY_SUF));
                $addBottom = str_replace('base', $param['url'], file_get_contents(TPL_PATH . 'addBottom' . SMARTY_SUF));
                $formData = "";
                foreach ($table as $item) {
                    $field = $item['Field'];
                    $key = $item['Key'];
                    if ($key != 'PRI') {
                        if (strpos($field, '_img') !== false
                            || strpos($field, '_image') !== false) {
                            $formData .= " <input id='pic' type='hidden' name='$field' value=''/>
<div class='layui-form-item' style='margin-left: 100px'>
        <img id='preImg' src='' style='width: 50px;height: 50px;margin-right: 10px' alt='预览图片'/>
        <button type='button' class='layui-btn' id='test1'>
            <i class='layui-icon'>&#xe67c;</i>上传图片
        </button>
    </div>";
                        } elseif (strpos($field, '_text') !== false) {
                            $formData .= "<div class='layui-form-item layui-form-text'>
    <label class='layui-form-label'>$field</label>
    <div class='layui-input-block'>
      <textarea name='$field' placeholder='请输入内容' class='layui-textarea'></textarea>
    </div>
  </div>";
                        } elseif (strpos($field, 'status') !== false) {
                            $formData .= "<div class='layui-form-item'>
    <label class='layui-form-label'>状态</label>
    <div class='layui-input-block'>
        <input type='radio' name='status' value='1' title='开启' checked>
        <input type='radio' name='status' value='0' title='关闭'>
    </div>
</div>";
                        } else {
                            $formData .= "<div class='layui-form-item'>
    <label class='layui-form-label'>$field</label>
    <div class='layui-input-block'>
        <input type='text' name='$field' placeholder='请输入$field' class='layui-input'>
    </div>
</div>";
                        }
                    }
                }
                $data = $addTop . $formData . $addBottom;
                fwrite($fp, $data);
                fclose($fp);


                $fp = fopen($filePath3, 'w');
                $updateTop = str_replace('base', $param['url'], file_get_contents(TPL_PATH . 'updateTop' . SMARTY_SUF));
                $updateBottom = str_replace('base', $param['url'], file_get_contents(TPL_PATH . 'updateBottom' . SMARTY_SUF));
                $formData = "";
                foreach ($table as $item) {
                    $field = $item['Field'];
                    $key = $item['Key'];
                    if ($key != 'PRI') {
                        if (strpos($field, '_img') !== false
                            || strpos($field, '_image') !== false) {
                            $formData .= "<input id='pic' type='hidden' name='$field'  value='{\$info.$field}'/>
<div class='layui-form-item' style='margin-left: 100px'>
    <img id='preImg' src='../../../../{{{\$info.$field}}}' style='width: 50px;height: 50px;' alt='预览图片'/>
    <button type='button' class='layui-btn' id='test1'>
        <i class='layui-icon'>&#xe67c;</i>上传图片
    </button>
</div>";
                        } elseif (strpos($field, '_text') !== false) {
                            $formData .= "<div class='layui-form-item layui-form-text'>
    <label class='layui-form-label'>$field</label>
    <div class='layui-input-block'>
      <textarea name='$field' placeholder='请输入内容' class='layui-textarea'>{{{\$info.$field}}}</textarea>
    </div>
  </div>";
                        } elseif (strpos($field, 'status') !== false) {
                            $formData .= "<div class='layui-form-item'>
    <label class='layui-form-label'>状态</label>
    <div class='layui-input-block'>
        <input type='radio' name='status' value='1' title='开启' {{{if \$info.$field == 1}}}checked{{{/if}}} >
        <input type='radio' name='status' value='0' title='关闭' {{{if \$info.$field == 0}}}checked{{{/if}}}>
    </div>
</div>";
                        } else {
                            $formData .= "<div class='layui-form-item'>
    <label class='layui-form-label'>$field</label>
    <div class='layui-input-block'>
        <input type='text' value='{{{\$info.$field}}}' name='$field' placeholder='请输入$field' class='layui-input'>
    </div>
</div>";
                        }
                    } else {
                        $formData .= "<input type='hidden' name='$field'  value='{{{\$info.$field}}}'/>";
                    }
                }
                $data = $updateTop . $formData . $updateBottom;
                fwrite($fp, $data);
                fclose($fp);

                $dirPath2 = APP_PATH . 'application/controllers';
                if (!is_dir($dirPath2)) {
                    if (!Directory::createDirectoryRecursively($dirPath2)) {
                        return;
                    }
                }
                $fileName = $preName . 'Controller';
                $filePath1 = $dirPath2 . '/' . $fileName . NORMAL_EXT;
                $fp = fopen($filePath1, 'w');
                $data = file_get_contents(TPL_PATH . 'controller' . NORMAL_EXT);
                $data = str_replace('fileName', $fileName, $data);
                $data = str_replace('xxx', str_replace(DB_TABLE_PREFIX, '', $tableName), $data);
                $data = str_replace('tableName', $tableName, $data);
                fwrite($fp, $data);
                fclose($fp);

                $routePrefix = $info['url'];
                $url = $param['url'];
                $routePath = APP_PATH . 'route/app.php';

                $fp = fopen($routePath, 'a+');
                $routeData = "

Router::addRoute('/admin/$routePrefix$url','$preName','index');
Router::addRoute('/admin/$routePrefix$url/add','$preName','add');
Router::addRoute('/admin/$routePrefix$url/update','$preName','update');
Router::addRoute('/admin/$routePrefix$url/delete','$preName','delete');";
                fwrite($fp, $routeData);
//                exit();
            }
            $res = Db::table('admin_menus')
                ->insert([
                    'parent_id' => $param['parent_id'],
                    'name' => $param['name'],
                    'url' => $param['url'],
                    'order_num' => $param['order_num'],
                    'status' => $param['status'],
                ]);
            if (empty($res)) {
                $this->json('操作失败', null, 400);
                exit();
            }
            $this->json('操作成功');
        }
    }

    public function baseUpdate()
    {
        $params = Request::param();
        if (Request::isGet()) {
            $ls = Db::table('admin_menus')
                ->select();
            $parents = [];
            $info = [];
            foreach ($ls as $item) {
                if ($item['id'] != $params['id']) {
                    $parents[] = $item;
                } else {
                    $info = $item;
                }
            }
//            var_dump($parents);
//            var_dump($info);
            $this->_view->set('parents', $parents);
            $this->_view->set('info', $info);
            $this->_view->render();
        } else {
            $res = Db::table('admin_menus')
                ->where('id', $params['id'])
                ->update($params);
            if (empty($res)) {
                $this->json('操作失败', null, 400);
                exit();
            }
            $this->json('操作成功');
        }
    }

    public function baseDelete()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        if (empty($id) && empty($ids)) {
            $this->json('缺少id');
            exit();
        }

        if (!empty($id)) {
            $res = Db::table('admin_menus')->where('id', $id)->delete();
        } else {
            $res = Db::table('admin_menus')->where('id', 'in', $ids)->delete();
        }
        if (empty($res)) {
            $this->json('删除失败', null, 400);
            exit();
        }
        $this->json('删除成功');
    }

}